<!--src/views/auth/RegisterView.vue-->
<template>
  <div class="register-wrapper">
    <div class="legal-pattern"></div>
    <div class="register-card">
      <!-- 顶部固定区域 -->
      <div class="header-section">
        <h1 class="page-title">用户注册</h1>
        <p class="page-subtitle">请填写完整信息完成注册</p>

        <div class="register-tabs">
          <button
              :class="['tab', { active: registerType === 'public' }]"
              @click="registerType = 'public'">
            公众用户注册
          </button>
          <button
              :class="['tab', { active: registerType === 'lawyer' }]"
              @click="registerType = 'lawyer'">
            律师用户注册
          </button>
        </div>
      </div>

      <!-- 滚动区域 -->
      <div class="form-scroller">
        <!-- 公众用户注册表单 -->
        <div
            v-if="registerType === 'public'"
            class="register-form public-form">
          <form @submit.prevent="handleRegister('public')">
            <div class="form-section">
              <h3 class="section-title">基本信息</h3>
              <div class="form-grid">
        

                <div class="form-group">
                  <label for="password">
                    <i class="icon-lock"></i> 密码 <span class="required">*</span>
                  </label>
                  <input
                      type="password"
                      id="password"
                      v-model.trim="publicForm.password"
                      placeholder="请输入密码"
                  />
                </div>

                <!-- 新增：确认密码 -->
                <div class="form-group">
                  <label for="confirm_password">
                    <i class="icon-lock"></i> 确认密码 <span class="required">*</span>
                  </label>
                  <input
                      type="password"
                      id="confirm_password"
                      v-model.trim="publicForm.confirm_password"
                      placeholder="请再次输入密码"
                  />
                </div>

                <div class="form-group">
                  <label for="mobile">
                    <i class="icon-mobile"></i> 手机号 <span class="required">*</span>
                  </label>
                  <input
                      type="tel"
                      id="mobile"
                      v-model.trim="publicForm.mobile"
                      placeholder="请输入手机号"
                  />
                </div>

                <!-- 新增：验证码 -->
                <div class="form-group">
                  <label for="code">
                    <i class="icon-code"></i> 验证码 <span class="required">*</span>
                  </label>
                  <div class="code-input-wrapper">
                    <input
                        type="text"
                        id="code"
                        v-model.trim="publicForm.code"
                        placeholder="请输入验证码"
                    />
                    <button
                        type="button"
                        class="send-code-btn"
                        :disabled="isSendingCode"
                        @click="sendCode">
                      {{ isSendingCode ? `${countdown}秒后重发` : '获取验证码' }}
                    </button>
                  </div>
                </div>

              </div>
            </div>


            <div v-if="errorMessage" class="error-message">
              <i class="icon-warning"></i> {{ errorMessage }}
            </div>

            <button type="submit" class="register-btn" :disabled="isLoading">
              <span>{{ isLoading ? '注册中...' : '注 册' }}</span>
            </button>
          </form>
        </div>

        <!-- 律师用户注册表单 -->
        <div
            v-else
            class="register-form lawyer-form">
          <form @submit.prevent="handleRegister('lawyer')">
            <div class="form-section">
              <h3 class="section-title">账户信息</h3>
              <div class="form-grid">
                <div class="form-group">
                  <label for="lawyer_username">
                    <i class="icon-user"></i> 用户名 <span class="required">*</span>
                  </label>
                  <input
                      type="text"
                      id="lawyer_username"
                      v-model.trim="lawyerForm.username"
                      placeholder="请输入用户名"
                  />
                </div>

                <div class="form-group">
                  <label for="lawyer_password">
                    <i class="icon-lock"></i> 密码 <span class="required">*</span>
                  </label>
                  <input
                      type="password"
                      id="lawyer_password"
                      v-model.trim="lawyerForm.password"
                      placeholder="请输入密码"
                  />
                </div>

                <!-- 新增：确认密码 -->
                <div class="form-group">
                  <label for="lawyer_confirm_password">
                    <i class="icon-lock"></i> 确认密码 <span class="required">*</span>
                  </label>
                  <input
                      type="password"
                      id="lawyer_confirm_password"
                      v-model.trim="lawyerForm.confirm_password"
                      placeholder="请再次输入密码"
                  />
                </div>

                <div class="form-group">
                  <label for="lawyer_mobile">
                    <i class="icon-mobile"></i> 手机号 <span class="required">*</span>
                  </label>
                  <input
                      type="tel"
                      id="lawyer_mobile"
                      v-model.trim="lawyerForm.mobile"
                      placeholder="请输入手机号"
                  />
                </div>

                <!-- 新增：验证码 -->
                <div class="form-group">
                  <label for="lawyer_code">
                    <i class="icon-code"></i> 验证码 <span class="required">*</span>
                  </label>
                  <div class="code-input-wrapper">
                    <input
                        type="text"
                        id="lawyer_code"
                        v-model.trim="lawyerForm.code"
                        placeholder="请输入验证码"
                    />
                    <button
                        type="button"
                        class="send-code-btn"
                        :disabled="isSendingCode"
                        @click="sendCode">
                      {{ isSendingCode ? `${countdown}秒后重发` : '获取验证码' }}
                    </button>
                  </div>
                </div>

                <div class="form-group">
                  <label for="license_no">
                    <i class="icon-license"></i> 律师执照号 <span class="required">*</span>
                  </label>
                  <input
                      type="text"
                      id="license_no"
                      v-model.trim="lawyerForm.license_no"
                      placeholder="请输入律师执照号"
                  />
                </div>
              </div>
            </div>

            <div class="form-section">
              <h3 class="section-title">个人信息</h3>
              <div class="form-grid">


                <div class="form-group">
                  <label for="real_name">
                    <i class="icon-person"></i> 真实姓名
                  </label>
                  <input
                      type="text"
                      id="real_name"
                      v-model.trim="lawyerForm.real_name"
                      placeholder="请输入真实姓名"
                  />
                </div>

                <div class="form-group">
                  <label for="id_card">
                    <i class="icon-id"></i> 身份证号
                  </label>
                  <input
                      type="text"
                      id="id_card"
                      v-model.trim="lawyerForm.id_card"
                      placeholder="请输入身份证号"
                  />
                </div>
                <div class="form-group">
                  <label for="email">
                    <i class="icon-email"></i> 邮箱
                  </label>
                  <input
                      type="email"
                      id="email"
                      v-model.trim="lawyerForm.email"
                      placeholder="请输入邮箱"
                  />
                </div>
                <div class="form-group">
                  <label for="avatar">
                    <i class="icon-image"></i> 头像URL
                  </label>
                  <input
                      type="text"
                      id="avatar"
                      v-model.trim="lawyerForm.avatar"
                      placeholder="请输入头像URL"
                  />
                </div>
              </div>
            </div>

            <div class="form-section">
              <h3 class="section-title">专业信息</h3>

              <div class="form-grid">
                <div class="form-group">
                  <label for="years_of_practice">
                    <i class="icon-calendar"></i> 执业年限
                  </label>
                  <input
                      type="number"
                      id="years_of_practice"
                      v-model.trim="lawyerForm.years_of_practice"
                      placeholder="请输入执业年限"
                  />
                </div>
                <div class="form-group">
                  <label for="specialty">
                    <i class="icon-specialty"></i> 专业领域
                  </label>
                  <input
                      type="text"
                      id="specialty"
                      v-model.trim="lawyerForm.specialty"
                      placeholder="请输入专业领域"
                  />
                </div>
                <div class="form-group">
                  <label for="success_rate">
                    <i class="icon-percent"></i> 案件成功率
                  </label>
                  <input
                      type="number"
                      id="success_rate"
                      v-model.trim="lawyerForm.success_rate"
                      placeholder="0-100"
                      min="0"
                      max="100"
                  />
                </div>

                <div class="form-group">
                  <label for="service_area">
                    <i class="icon-location"></i> 服务区域
                  </label>
                  <input
                      type="text"
                      id="service_area"
                      v-model.trim="lawyerForm.service_area"
                      placeholder="请输入服务区域"
                  />
                </div>


              </div>
            </div>

            <div class="form-section">
              <h3 class="section-title">个人介绍</h3>
              <div class="form-group">
                <label for="introduction">
                  <i class="icon-doc"></i> 个人介绍
                </label>
                <textarea
                    id="introduction"
                    v-model.trim="lawyerForm.introduction"
                    placeholder="请简要介绍您的专业背景和服务理念"
                    rows="3"
                ></textarea>
              </div>
            </div>

            <div v-if="errorMessage" class="error-message">
              <i class="icon-warning"></i> {{ errorMessage }}
            </div>

            <button type="submit" class="register-btn" :disabled="isLoading">
              <span>{{ isLoading ? '注册中...' : '注 册' }}</span>
            </button>
          </form>
        </div>
      </div>

      <div class="footer-links">
        <router-link to="/login">
          <i class="icon-login"></i> 已有账号？立即登录
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api/user'
import "@/styles/registerview.css"

export default {
  name: 'RegisterView',
  setup() {
    const router = useRouter()
    const registerType = ref('public')

    // 表单数据
    const publicForm = ref({
      password: '',
      confirm_password: '',
      mobile: '',
      code: '',
    })

    const lawyerForm = ref({
      username: '',
      password: '',
      confirm_password: '',
      mobile: '',
      code: '',
      license_no: '',
      email: '',
      real_name: '',
      id_card: '',
      avatar: '',
      specialty: '',
      years_of_practice: '',
      success_rate: '',
      service_area: '',
      introduction: ''
    })

    const isLoading = ref(false)
    const isSendingCode = ref(false)
    const countdown = ref(10)
    const errorMessage = ref('')

    // 手机号正则表达式，可根据实际需求调整，这里是大陆手机号简单正则
    const phoneRegExp = /^1[3-9]\d{9}$/; 

    // 发送验证码
    const sendCode = async () => {
      const mobile = registerType.value === 'public'
          ? publicForm.value.mobile
          : lawyerForm.value.mobile

      if (!mobile) {
        errorMessage.value = '请输入手机号'
        return
      }

      // 新增手机号正则校验逻辑
      if (!phoneRegExp.test(mobile)) {
        errorMessage.value = '手机号格式不正确，请检查后重新输入';
        return;
      }

      isSendingCode.value = true
      try {
        userAPI.sendCode({
          mobile: mobile
        }).then(res => { 
          if (res.data.code == 200) {
            ElMessage.success('验证码已发送')
          } else {
            ElMessage.error(res.msg)
          }
        })

        // 倒计时逻辑
        const timer = setInterval(() => {
          if (countdown.value <= 0) {
            clearInterval(timer)
            isSendingCode.value = false
            countdown.value = 10
            return
          }
          countdown.value--
        }, 1000)
      } catch (error) {
        ElMessage.error(error.message || '发送验证码失败')
        isSendingCode.value = false
      }
    }

    // 处理注册
    const handleRegister = async (type) => {
      const form = type === 'public' ? publicForm.value : lawyerForm.value

      // 验证必填字段
      if ( !form.password || !form.mobile || !form.code) {
        errorMessage.value = '请填写所有必填项'
        return
      }

      // 验证密码一致性
      if (form.password !== form.confirm_password) {
        errorMessage.value = '两次输入的密码不一致'
        return
      }

      // 律师注册额外验证
      if (type === 'lawyer' && !form.license_no) {
        errorMessage.value = '请填写律师执照号'
        return
      }

      isLoading.value = true
      errorMessage.value = ''

    
      try {
          let res
        if (type === 'public') {
          // 提取需要的字段，避免提交不必要的数据
          const { confirm_password, code, ...submitData } = form
          submitData.smsCode = code
          res = await userAPI.registerPublic(submitData)
        } else {
          const { confirm_password, code, ...submitData } = form
          res = await userAPI.registerLawyer(submitData)
        }
        if (res.data.code == 200) {
          ElMessage.success(`${type === 'public' ? '公众用户' : '律师用户'}注册成功！请登录`)
          router.push('/login')
        } else {
          ElMessage.error(res.data.message)
        }
      } catch (error) {
        // 处理错误情况
        if (error && error.message) {
          ElMessage.error(error.message)
        } else if (error && error.msg) {
          ElMessage.error(error.msg)
        } else {
          ElMessage.error('注册失败，请稍后重试')
        }
        console.error('注册失败:', error)
      } 
      finally {
        isLoading.value = false
      }
    }

    return {
      registerType,
      publicForm,
      lawyerForm,
      isLoading,
      isSendingCode,
      countdown,
      errorMessage,
      sendCode,
      handleRegister
    }
  }
}
</script>

<style scoped>

</style>